package webservice.httpclient;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.CloseShieldInputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.springframework.util.StopWatch;

import java.io.IOException;
import java.io.InputStream;

/**
 * Author: Jason Wu
 * Date  : 2013-11-28
 */
public class HttpClientInvoker {
    public static final int CONNECTION_TIMEOUT = 5000;
    public static final int READ_TIMEOUT = 6000;
    private static final String ENCODING = "UTF-8";

    public static void main(String[] args) throws IOException {

        String url = "http://extratest.ostrovok.ru/echannel/api/v0.1/hotels/?format=json" +
                "&token=daf928f68fddd94f7014c9d666950f9c&sign=32c5afbcb54ffc3d1b850a15ec5b26ba&";
        HttpClient httpClient = createHttpClient();

        HttpGet httpGet = new HttpGet("http://localhost:8080/bestday-push/hotel/dmxQueryHotel.dhtml");
        httpGet.setHeader("Content-type", "text/xml; charset=UTF-8");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);

            InputStream inputStream = httpResponse.getEntity().getContent();
            String response = IOUtils.toString(new CloseShieldInputStream(inputStream), ENCODING);
            System.out.println(response);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            stopWatch.stop();
            System.out.println("----------" + stopWatch.getTotalTimeMillis());
        }
    }

    private static HttpClient createHttpClient() {
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CookiePolicy.IGNORE_COOKIES, true);
        httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
        httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, READ_TIMEOUT);
        return httpClient;
    }
}
